<script setup lang="ts">
import {onMounted, onUnmounted, ref} from "vue";
import axios from "axios";
import config from "../assets/config.json"
import {PeriUpdateResponse} from "../class/PeriUpdateResponse";


const props = defineProps({
  deviceNumber: String,
  chartViewOption: {
    type: String,
    default: "line"
  },
  chartUpdateDelay: {
    type: Number,
    default: 180000
  }
});

const emits = defineEmits([
    "chartViewOptionChanged",
    "chartUpdateDelayChanged"
]);

let chartViewOption = ref(props.chartViewOption);
let chartUpdateDelay = ref(props.chartUpdateDelay/1000/60);
let dataUpdateDelay = ref(0);
let periUpdateStatus = ref(false);
let switchesDisabled = ref(true);
onMounted(() => {
  if (props.deviceNumber != undefined) {
    getPeriUpdate(props.deviceNumber).then(periUpdateResponse => {
      periUpdateStatus.value = periUpdateResponse.status;
      dataUpdateDelay.value = periUpdateResponse.minutes;
      switchesDisabled.value = false;
    });
  }
});

const switchDataUpdate = () => {
  periUpdateStatus.value = !periUpdateStatus.value;
  if (periUpdateStatus.value) {
    // 自动更新数据开启
    periUpdateStart(props.deviceNumber as string).then(optStatus => {
      if (dataUpdateDelay.value < 3) dataUpdateDelay.value = 3;
      periUpdateStatus.value = optStatus == "success";
    }).catch(err => {
      console.log(err);
    }).finally(() => {
      // 确认设置是否成功
      getPeriUpdate(props.deviceNumber as string).then(periUpdateResponse => {
        // 设置开关状态和时间间隔
        periUpdateStatus.value = periUpdateResponse.status;
        dataUpdateDelay.value = periUpdateResponse.minutes;
        switchesDisabled.value = false;
      });
    });
  } else {
    // 自动更新数据关闭
    periUpdateStop(props.deviceNumber as string).then(optStatus => {
      periUpdateStatus.value = !(optStatus == "success");
    }).catch(err => {
      console.log(err);
    }).finally(() => {
      // 确认设置是否成功
      getPeriUpdate(props.deviceNumber as string).then(periUpdateResponse => {
        // 设置开关状态和时间间隔
        periUpdateStatus.value = periUpdateResponse.status;
        switchesDisabled.value = false;
      });
    });
  }
};

function periUpdateStart(deviceNumber: string) : Promise<string> {
  return new Promise<string>((resolve, reject) => {
    const paramDelay = dataUpdateDelay.value == 0 ? 3 : dataUpdateDelay.value;
    axios({
      baseURL: `http://${config.host}:${config.port}`,
      url: `${config.apiPrefix}/${deviceNumber}/${config.apiSuffix.periUpdateStart}`,
      method: "GET",
      params: {
        minutes: paramDelay
      }
    }).then(response => {
      if (response.status === 200) {
        resolve(response.data.status);
      } else {
        throw Error("status is not success.");
      }
    }).catch(err => {
      reject(err);
    });
  });
}

function periUpdateStop(deviceNumber: string) : Promise<string> {
  return new Promise<string>((resolve, reject) => {
    axios({
      baseURL: `http://${config.host}:${config.port}`,
      url: `${config.apiPrefix}/${deviceNumber}/${config.apiSuffix.periUpdateStop}`,
      method: "GET"
    }).then(response => {
      if (response.status === 200) {
        resolve(response.data.status);
      } else {
        throw Error("status is not success.");
      }
    }).catch(err => {
      reject(err);
    });
  });
}

function getPeriUpdate(deviceNumber: string) : Promise<PeriUpdateResponse> {
  return new Promise<PeriUpdateResponse>((resolve, reject) => {
    axios({
      baseURL: `http://${config.host}:${config.port}`,
      url: `${config.apiPrefix}/${deviceNumber}/${config.apiSuffix.periUpdateStatus}`,
      method: "GET"
    }).then(response => {
      if (response.status === 200 && response.data.status === "success") {

        resolve(new PeriUpdateResponse(response.data['periUpdateStatus'], response.data['minutes']));
      } else {
        throw Error("status is not success.");
      }
    }).catch(err => {
      reject(err);
    });
  });
}

function chartUpdateDelayChange(e: any) {
  chartUpdateDelay.value = e;
  emits("chartUpdateDelayChanged", chartUpdateDelay.value*1000*60);
}

function chartViewSwitchChange(e: any) {
  chartViewOption.value = e;
  emits("chartViewOptionChanged", chartViewOption.value);
}

function dataUpdateDelayChange(e: any) {
  dataUpdateDelay.value = e;
  if (periUpdateStatus.value) {
    periUpdateStatus.value = false;
    periUpdateStop(props.deviceNumber as string);
  }
}
</script>

<template>
  <div style="margin-inline: 40px;">
    <t-row class="rows">
      <t-col :span="2">
        <span>后台数据更新</span>
      </t-col>
      <t-col :span="2" class="rightCols">
        <t-input-number :min="3" :max="15" theme="column" style="margin-inline: 10px" placeholder="间隔" :allow-input-over-limit="false" suffix="分钟" :value="dataUpdateDelay" :auto-width="true" @change="dataUpdateDelayChange($event)" />
        <t-switch :disabled="switchesDisabled" size="large" :value="periUpdateStatus" @change="switchDataUpdate"></t-switch>
      </t-col>
    </t-row>

    <t-row class="rows">
      <t-col :span="2">
        <span>图表形式</span>
      </t-col>
      <t-col :span="2" class="rightCols">
        <t-radio-group variant="outline" :value="chartViewOption" @change="chartViewSwitchChange($event)">
          <t-radio-button value="line">折线图</t-radio-button>
          <t-radio-button value="bar">柱状图</t-radio-button>
        </t-radio-group>
      </t-col>
    </t-row>

    <t-row class="rows">
      <t-col :span="2">
        <span>图表更新间隔</span>
      </t-col>
      <t-col :span="2" class="rightCols">
        <t-input-number :min="3" :max="15" :allow-input-over-limit="false" suffix="分钟" :value="chartUpdateDelay" :auto-width="true" @change="chartUpdateDelayChange($event)" />
      </t-col>
    </t-row>

  </div>
</template>


<style scoped>
.rows {
  margin-block: 10px;
}

.rightCols {
  text-align: right;
}
</style>